package org.jsets.rpc.server;

import java.net.InetSocketAddress;

import org.jsets.rpc.conf.SerivceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @ClassName: Server
 * @Description: 服务器
 * @author wangjie
 * @date 2015年月7日 下午3:32:02
 *
 */
public class NettyServer {
	private static Logger logger = LoggerFactory.getLogger(NettyServer.class.getSimpleName());
	
	private ServerBootstrap b = null;
	protected SerivceConfig serivceConfig;
	private ChannelHandler channelHandler;

	public NettyServer(ChannelHandler remoteJobContext, SerivceConfig serivceConfig) {
		this.channelHandler = remoteJobContext;
		this.serivceConfig = serivceConfig;
	}

	public void start() {
		logger.info(" server start on " + this.serivceConfig.getPort() + " ... ...");
		initialize();
	}

	public void initialize() {
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workGroup = new NioEventLoopGroup();
		
		try {
			b = new ServerBootstrap();
			b.group(bossGroup, workGroup);
			b.channel(NioServerSocketChannel.class);
			b.childHandler(new ChannelInitializer<Channel>() {
				@Override
				protected void initChannel(Channel e) throws Exception {
					e.pipeline().addLast("decoder", new HttpRequestDecoder());
					e.pipeline().addLast("encoder", new HttpResponseEncoder());
					
//					e.pipeline().addLast("http-codec", new HttpServerCodec());
					e.pipeline().addLast("aggregator", new HttpObjectAggregator(1048576));
					
					e.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); //处理大数据流
//					e.pipeline().addLast("deflater", new HttpContentCompressor()); //内容压缩
					
					e.pipeline().addLast("handler", channelHandler);
				}
			});
						
			logger.info("服务端开启等待客户端连接 ... ...");
			Channel ch = b.bind(new InetSocketAddress(serivceConfig.getPort())).sync().channel();
			ch.closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

	public void stop() {
		logger.info("Server stop!");
	}
}